<?php

namespace app\controllers;

use Yii;
use app\tools\Re;
use app\models\Area;
use app\models\User;
use app\models\Task;
use app\models\Repair;
use app\models\TaskRepair;
use app\models\TaskRepairLocation;
use app\models\Device;
use app\models\FormTag;
use app\models\CompanyInfo;
use app\models\RepairEvaluate;
use app\models\Setting;
use app\filters\auth\HttpBearerAuth;
use yii\helpers\ArrayHelper;
use app\tools\JPushHelper;

class TaskController extends BaseController
{
  public function behaviors() {
      $optional =  [
        'device-list',
        'task-info',
        'repair-list',
        'repair-user-list'
      ];
      return ArrayHelper::merge(parent::behaviors(), [
        'authenticator' => [
          'class' => HttpBearerAuth::class,
          'optional' =>$optional
        ]
      ]);
  }

  public $task_state_arr = ['等待接单', '已接单', '已完成', '已评价', '已取消', '维修中'];
  public $repair_state_arr = ['等待接单', '已接单', '已出发', '已到达', '维修取消', '维修中', '维修完成', '已评价'];

  //设备/故障列表
  public function actionDeviceList(){
    $level = Yii::$app->request->post('level', 1);
    $parent_id = Yii::$app->request->post('parent_id', 0);
    $device_list = Device::find()->where(['parent_id' => $parent_id, 'level' => $level, 'status' => 1])->select('id, name')->all();
    return Re::data(['data' => $device_list]);
  }

  //用户发起抢修
  public function actionAddTask(){
    $user_name = Yii::$app->request->post('user_name', '');
    $user_phone = Yii::$app->request->post('user_phone', '');
    $province = Yii::$app->request->post('province', '');
    $city = Yii::$app->request->post('city', '');
    $area = Yii::$app->request->post('area', '');
    $address = Yii::$app->request->post('address', '');
    $address_detail = Yii::$app->request->post('address_detail', '');
    $longitude = Yii::$app->request->post('longitude', '');
    $latitude = Yii::$app->request->post('latitude', '');
    $content = Yii::$app->request->post('content', '');
    $imgs = Yii::$app->request->post('imgs', '');
    $device_main_id = Yii::$app->request->post('device_main_id', 0);
    $device_id = Yii::$app->request->post('device_id', 0);
    $gz_type_ids = Yii::$app->request->post('gz_type_ids', '');
    $is_need_bd = Yii::$app->request->post('is_need_bd', 1);
    $voltage_level = Yii::$app->request->post('voltage_level', 0);
    if (empty($province) || empty($city) || empty($area) || empty($address) || empty($longitude) || empty($latitude) || empty($content)) {
      return Re::data(null, '参数错误', Re::ERROR);
    }
    $user = Yii::$app->user->identity;
    /*if (!$user->company_id) {
      return Re::data(null, '您还未进行企业认证，暂时无法发布抢修任务', Re::ERROR);
    }*/
    if ($voltage_level == 18) {
      return Re::data(null, '10kV及以下不满足报修条件，请联系客服处理', Re::ERROR);
    }
    $task = new Task();
    $task->user_id = Yii::$app->user->id;
    $task->user_name = $user_name;
    $task->user_phone = $user_phone;
    $task->content = $content;
    $task->lng = $longitude;
    $task->lat = $latitude;
    $task->province = $province;
    $task->city = $city;
    $task->area = $area;
    $task->address = $address;
    $task->address_detail = $address_detail;
    $task->device_main_id = $device_main_id;
    $task->device_id = $device_id;
    $task->gz_type_ids = $gz_type_ids;
    $task->imgs = $imgs;
    $task->is_need_bd = $is_need_bd;
    $task->voltage_level = $voltage_level;
    $task->status = 1;
    $task->created_at = time();
    if (!$task->save()) {
      return Re::data(null, '操作失败', Re::ERROR);
    }
    $area_info = Area::find()->where(['name' => $area, 'level' => 2])->one();
    $repair_id_arr = Repair::find()->where(['area_id' => $area_info->id, 'status' => 1])->select("id")->column();
    if ($repair_id_arr) {
      $repair_ids = implode(',', $repair_id_arr);
      $user_qx_id_arr = User::find()->where(['status' => 1])->andWhere("repair_id in (".$repair_ids.")")->select("id")->column();
      $extra = [
        'push_type' => 'qxdd',
        'push_user_type' => 2
      ];
      JPushHelper::pushNotifyByReg($user_qx_id_arr, '抢修订单通知', '有新的抢修单，请至后台查看', $extra);
    }
    $setting = Setting::findOne(1);
    if ($setting->open_push_admin) {
      $user_admin_id_arr = User::find()->where(['status' => 1, 'is_admin' => 1])->select("id")->column();
      $extra = [
        'push_type' => 'qxdd',
        'push_user_type' => 3
      ];
      JPushHelper::pushNotifyByReg($user_admin_id_arr, '抢修订单通知', '有新的抢修单，请至后台查看', $extra);
    }
    return Re::data();
  }

  //个人发布的任务列表
  public function actionMyTaskList(){
    $state = Yii::$app->request->post('state', -1);
    $page = Yii::$app->request->post('page', 0);
    $task_query = Task::find()->where(['user_id' => Yii::$app->user->id, 'status' => 1]);
    if ($state > -1) {
      $task_query->andWhere(['state' => $state]);
    }
    $task_list = $task_query->orderBy('created_at desc')->limit(10)->offset(10*$page)->all();
    $task_data = [];
    if ($task_list) {
      foreach ($task_list as $v) {
        $task_repair = TaskRepair::find()->where(['task_id' => $v->id])->one();
        $repair_evaluate = RepairEvaluate::find()->where(['task_id' => $v->id])->one();
        if (!$task_repair) {
          $state_name = $v->state == 4 ? '已取消' : '等待接单';
        } else if ($v->state == 1) {
          $state_name = $task_repair->admin_assign ? '已派单' : '已接单';
        } else {
          $state_name = $this->repair_state_arr[$task_repair->state];
        }
        $state = $task_repair ? (int)$task_repair->state : (int)$v->state;
        if (!$v->state && ($v->created_at+900) < time()) {
          $state = -1;
          $state_name = '已超时';
        }
        $task_data[] = [
          'task_id' => $v->id,
          'task_name' => $v->device->name.'故障',
          'state' => $state,
          'state_name' => $state_name,
          'user_name' => $v->user->name,
          'user_phone' => $v->user->phone,
          'out_time_msg' => $state == -1 ? '用户订单发起已超时15分钟' : '',
          'admin_assign' => $task_repair ? $task_repair->admin_assign : -1,
          'created_time' => date('Y-m-d H:i', $v->created_at),
          'get_task_time' => $task_repair ? date('Y-m-d H:i', $task_repair->created_at) : '',
          'go_time' => ($task_repair && $task_repair->go_at) ? date('Y-m-d H:i', $task_repair->go_at) : '',
          'arrive_time' => ($task_repair && $task_repair->arrive_at) ? date('Y-m-d H:i', $task_repair->arrive_at) : '',
          'arrive_time_real' => ($task_repair && $task_repair->arrive_at_real) ? date('Y-m-d H:i', $task_repair->arrive_at_real) : '',
          'cancel_time' => ($task_repair && $task_repair->cancel_at) ? date('Y-m-d H:i', $task_repair->cancel_at) : '',
          'finsh_time' => ($task_repair && $task_repair->finsh_at) ? date('Y-m-d H:i', $task_repair->finsh_at) : '',
          'evaluate_time' => $repair_evaluate ? date('Y-m-d H:i', $repair_evaluate->created_at) : '',
        ];
      }
    }
    return Re::data(['data' => $task_data]);
  }

  //抢修队面板(任务列表)
  public function actionTaskListForRepair(){
    $state = Yii::$app->request->post('state', -1);
    $page = Yii::$app->request->post('page', 0);
    $user_info = User::findOne(Yii::$app->user->id);
    if (!$user_info) {
      return Re::data(null, '用户信息异常', Re::ERROR);
    }
    if (!$user_info->repair_id) {
      return Re::data(null, '您还不是抢修队员，暂时无法操作', Re::ERROR);
    }
    $task_query = Task::find()
      ->leftJoin('task_repair', 'task.id=task_repair.task_id')
      ->where(['task.status' => 1]);
    if ($state == -1) {
        $area_info = Area::findOne($user_info->repair->area_id);
        $task_query->andWhere("(task.area='$area_info->name' && task.state=0) or task.state=4 or (task.state > 0 and task.state <> 4 and task_repair.user_id = '$user_info->id')");
    }
    if ($state == 4) {
      $task_query->andWhere(['task.state' => $state]);
    }
    if ($state > -1 && $state <> 4) {
      $task_query->andWhere(['task_repair.user_id' => Yii::$app->user->id, 'task.state' => $state]);
    }
    $task_list = $task_query->orderBy('created_at desc')->limit(10)->offset(10*$page)->all();
    $task_data = [];
    if ($task_list) {
      foreach ($task_list as $v) {
        $task_repair = TaskRepair::find()->where(['task_id' => $v->id])->one();
        $repair_evaluate = RepairEvaluate::find()->where(['task_id' => $v->id])->one();
        if (!$task_repair) {
          $state_name = $v->state == 4 ? '已取消' : '等待接单';
        } else if ($v->state == 1) {
          $state_name = $task_repair->admin_assign ? '已派单' : '已接单';
        } else {
          $state_name = $this->repair_state_arr[$task_repair->state];
        }
        $state = $task_repair ? (int)$task_repair->state : (int)$v->state;
        if (!$v->state && ($v->created_at+900) < time()) {
          $state = -1;
          $state_name = '已超时';
        }
        $task_data[] = [
          'task_id' => $v->id,
          'task_name' => $v->device->name.'故障',
          'state' => $state,
          'state_name' => $state_name,
          'user_name' => $v->user->name,
          'user_phone' => $v->user->phone,
          'out_time_msg' => $state == -1 ? '用户订单发起已超时15分钟' : '',
          'admin_assign' => $task_repair ? $task_repair->admin_assign : -1,
          'created_time' => date('Y-m-d H:i', $v->created_at),
          'get_task_time' => $task_repair ? date('Y-m-d H:i', $task_repair->created_at) : '',
          'go_time' => ($task_repair && $task_repair->go_at) ? date('Y-m-d H:i', $task_repair->go_at) : '',
          'arrive_time' => ($task_repair && $task_repair->arrive_at) ? date('Y-m-d H:i', $task_repair->arrive_at) : '',
          'arrive_time_real' => ($task_repair && $task_repair->arrive_at_real) ? date('Y-m-d H:i', $task_repair->arrive_at_real) : '',
          'cancel_time' => ($task_repair && $task_repair->cancel_at) ? date('Y-m-d H:i', $task_repair->cancel_at) : '',
          'finsh_time' => ($task_repair && $task_repair->finsh_at) ? date('Y-m-d H:i', $task_repair->finsh_at) : '',
          'evaluate_time' => $repair_evaluate ? date('Y-m-d H:i', $repair_evaluate->created_at) : '',
        ];
      }
    }
    return Re::data(['data' => $task_data]);
  }

  //管理员面板(任务列表)
  public function actionTaskListForAdmin(){
    $state = Yii::$app->request->post('state', -1);
    $page = Yii::$app->request->post('page', 0);
    $user_info = User::findOne(Yii::$app->user->id);
    if (!$user_info) {
      return Re::data(null, '用户信息异常', Re::ERROR);
    }
    if (!$user_info->is_admin) {
      return Re::data(null, '您还不是管理员，暂时无法操作', Re::ERROR);
    }
    $task_query = Task::find()
      ->leftJoin('task_repair', 'task.id=task_repair.task_id')
      ->where(['task.status' => 1]);
    if ($state == 0) {//未派单
      $task_query->andWhere(['task.state' => 0]);
    }
    if ($state == 1) {//已派单
      $task_query->andWhere(['task_repair.admin_assign' => 1]);
    }
    $task_list = $task_query->orderBy('created_at desc')->limit(10)->offset(10*$page)->all();
    $task_data = [];
    if ($task_list) {
      foreach ($task_list as $v) {
        $task_repair = TaskRepair::find()->where(['task_id' => $v->id])->one();
        $repair_evaluate = RepairEvaluate::find()->where(['task_id' => $v->id])->one();
        if (!$task_repair) {
          $state_name = $v->state == 4 ? '已取消' : '等待接单';
        } else if ($v->state == 1) {
          $state_name = $task_repair->admin_assign ? '已派单' : '已接单';
        } else {
          $state_name = $this->repair_state_arr[$task_repair->state];
        }
        $state = $task_repair ? (int)$task_repair->state : (int)$v->state;
        if (!$v->state && ($v->created_at+900) < time()) {
          $state = -1;
          $state_name = '已超时';
        }
        $task_data[] = [
          'task_id' => $v->id,
          'task_name' => $v->device->name.'故障',
          'state' => $state,
          'state_name' => $state_name,
          'user_name' => $v->user->name,
          'user_phone' => $v->user->phone,
          'out_time_msg' => $state == -1 ? '用户订单发起已超时15分钟' : '',
          'admin_assign' => $task_repair ? $task_repair->admin_assign : -1,
          'created_time' => date('Y-m-d H:i', $v->created_at),
          'get_task_time' => $task_repair ? date('Y-m-d H:i', $task_repair->created_at) : '',
          'go_time' => ($task_repair && $task_repair->go_at) ? date('Y-m-d H:i', $task_repair->go_at) : '',
          'arrive_time' => ($task_repair && $task_repair->arrive_at) ? date('Y-m-d H:i', $task_repair->arrive_at) : '',
          'arrive_time_real' => ($task_repair && $task_repair->arrive_at_real) ? date('Y-m-d H:i', $task_repair->arrive_at_real) : '',
          'cancel_time' => ($task_repair && $task_repair->cancel_at) ? date('Y-m-d H:i', $task_repair->cancel_at) : '',
          'finsh_time' => ($task_repair && $task_repair->finsh_at) ? date('Y-m-d H:i', $task_repair->finsh_at) : '',
          'evaluate_time' => $repair_evaluate ? date('Y-m-d H:i', $repair_evaluate->created_at) : '',
        ];
      }
    }
    return Re::data(['data' => $task_data]);
  }

  //任务详情
  public function actionTaskInfo(){
    $task_id = Yii::$app->request->post('task_id', '');
    $task_info = Task::findOne($task_id);
    if (!$task_info) {
      return Re::data(null, '抢修信息读取失败', Re::ERROR);
    }
    $gz_data = [];
    if ($task_info->gz_type_ids) {
      $gz_type_arr = explode(',', $task_info->gz_type_ids);
      foreach ($gz_type_arr as $v) {
        $device = Device::findOne($v);
        array_push($gz_data, $device->name);
      }
    }
    $task_repair = TaskRepair::find()->where(['task_id' => $task_id])->one();
    $repairEvaluate = RepairEvaluate::find()->where(['task_id' => $task_id])->one();
    $task_state = $task_info->state;
    if (!$task_state && ($task_info->created_at+900) < time()) {
      $task_state = -1;
      //$state_name = '已超时';
    }
    $task_data = [
      'repair_id' => $task_repair ? $task_repair->repair_id : 0,
      'repair_user_name' => $task_repair ? $task_repair->user->name : '',
      'repair_user_phone' => $task_repair ? $task_repair->user->phone : '',
      'repair_name' => $task_repair ? $task_repair->repair->name : '',
      'repair_user_longitude' => $task_repair ? $task_repair->lng : '',
      'repair_user_latitude' => $task_repair ? $task_repair->lat : '',
      'repair_start_content' => $task_repair ? $task_repair->start_content : '',
      'repair_start_imgs' => ($task_repair && $task_repair->start_imgs) ? explode(',', $task_repair->start_imgs) : [],
      'repair_finsh_content' => $task_repair ? $task_repair->finsh_content : '',
      'repair_finsh_imgs' => ($task_repair && $task_repair->finsh_imgs) ? explode(',', $task_repair->finsh_imgs) : [],
      'repair_finsh_time' => ($task_repair && $task_repair->finsh_at) ? date('Y-m-d H:i', $task_repair->finsh_at) : '',
      'repair_evaluate_time' => $repairEvaluate ? date('Y-m-d H:i', $repairEvaluate->created_at) : '',
      'repair_state' => $task_repair ? $task_repair->state : 0,
      'repair_state_name' => $task_repair ? $this->repair_state_arr[$task_repair->state] : '',
      'estimate_distance' => $task_repair ? $task_repair->estimate_distance : '',
      'estimate_time' => $task_repair ? $task_repair->estimate_time : '',
      'arrive_time' => ($task_repair && $task_repair->arrive_at) ? date('Y-m-d H:i', $task_repair->arrive_at) : '',
      'user_name' => $task_info->user->name ? $task_info->user->name : '',
      'user_phone' => $task_info->user->phone ? $task_info->user->phone : '',
      'task_longitude' => $task_info->lng,
      'task_latitude' => $task_info->lat,
      'task_state' => $task_state,
      'task_state_name' => $task_state == -1 ? '已超时' : $this->task_state_arr[$task_info->state],
      'task_device_main_name' => $task_info->device_main_id ? $task_info->deviceMain->name : '',
      'task_device_name' => $task_info->device_id ? $task_info->device->name : '',
      'task_gz_name' => $gz_data,
      'task_content' => $task_info->content,
      'task_is_need_bd' => $task_info->is_need_bd,
      'task_imgs' => $task_info->imgs ? explode(',', $task_info->imgs) : [],
      'task_area' => $task_info->province.$task_info->city.$task_info->area,
      'task_address' => $task_info->address,
      'task_address_detail' => $task_info->address_detail,
      'task_voltage' => $task_info->voltage_level ? $task_info->voltage->name : '',
      'created_time' => date('Y-m-d H:i', $task_info->created_at),
      'arrive_time_real' => ($task_repair && $task_repair->arrive_at_real) ? date('Y-m-d H:i', $task_repair->arrive_at_real) : '',
      'cost' => $task_repair ? $task_repair->cost : '',
    ];
    return Re::data(['data' => $task_data]);
  }

  //取消任务
  public function actionTaskCancel(){
    $task_id = Yii::$app->request->post('task_id', '');
    $task_info = Task::findOne($task_id);
    if (!$task_info) {
      return Re::data(null, '抢修信息读取失败', Re::ERROR);
    }
    if ($task_info->state) {
      return Re::data(null, '抢修员已接单，无法取消', Re::ERROR);
    }
    $task_info->state = 4;
    $task_info->save();
    return Re::data();
  }

  //任务评价
  public function actionRepairEvaluate(){
    $task_id = Yii::$app->request->post('task_id', '');
    $star_finsh_time = Yii::$app->request->post('star_finsh_time', 1);
    $star_finsh_quality = Yii::$app->request->post('star_finsh_quality', 1);
    $star_service = Yii::$app->request->post('star_service', 1);
    $content = Yii::$app->request->post('content', '');
    $task_info = Task::findOne($task_id);
    if (!$task_info) {
      return Re::data(null, '任务信息读取失败', Re::ERROR);
    }
    $task_repair = TaskRepair::find()->where(['task_id' => $task_id])->one();
    if (!$task_repair) {
      return Re::data(null, '抢修信息读取失败', Re::ERROR);
    }
    $repairEvaluate = new RepairEvaluate();
    $repairEvaluate->task_id = $task_id;
    $repairEvaluate->repair_id = $task_repair->repair_id;
    $repairEvaluate->user_id = $task_repair->user_id;
    $repairEvaluate->star_finsh_time = $star_finsh_time;
    $repairEvaluate->star_finsh_quality = $star_finsh_quality;
    $repairEvaluate->star_service = $star_service;
    $repairEvaluate->content = $content;
    $repairEvaluate->status = 1;
    $repairEvaluate->created_at = time();
    if (!$repairEvaluate->save()) {
      return Re::data(null, '评价失败', Re::ERROR);
    }
    $star_finsh_time_total = RepairEvaluate::find()->where(['repair_id' => $task_repair->repair_id])->SUM('star_finsh_time');
    $star_finsh_quality_total = RepairEvaluate::find()->where(['repair_id' => $task_repair->repair_id])->SUM('star_finsh_quality');
    $star_service_total = RepairEvaluate::find()->where(['repair_id' => $task_repair->repair_id])->SUM('star_service');
    $star_total = $star_finsh_time_total + $star_finsh_quality_total + $star_service_total;
    $repair_count = RepairEvaluate::find()->where(['repair_id' => $task_repair->repair_id])->count();
    $repair = $task_repair->repair;
    $repair->star_avg = number_format($star_total/$repair_count, 1);
    $repair->save();
    $task_repair->state = 7;
    $task_repair->save();
    $task_info->state = 3;
    $task_info->save();
    $extra = [
      'push_type' => 'qxpj',
      'push_user_type' => 2
    ];
    JPushHelper::pushNotifyByReg((string)$task_repair->user_id, '用户评价通知', '有新的抢修单评价，请至后台查看', $extra);
    return Re::data();
  }

  //查看任务评价
  public function actionViewRepairEvaluate(){
    $task_id = Yii::$app->request->post('task_id', '');
    $repairEvaluate = RepairEvaluate::find()->where(['task_id' => $task_id])->one();
    if (!$repairEvaluate) {
      return Re::data(null, '信息读取失败', Re::ERROR);
    }
    return Re::data(['data' => $repairEvaluate]);
  }

  //维修员接单
  public function actionTaskRepair(){
    $task_id = Yii::$app->request->post('task_id', '');
    $task_info = Task::findOne($task_id);
    if (!$task_info) {
      return Re::data(null, '任务信息读取失败', Re::ERROR);
    }
    if ($task_info->state == 4) {
      return Re::data(null, '任务已被取消，暂时无法接单', Re::ERROR);
    }
    if (Yii::$app->user->id == $task_info->user_id) {//此处限制维修员不能接自己发出的任务
      //return Re::data(null, '该抢修任务由自己发出，暂时无法接单', Re::ERROR);
    }
    $user = Yii::$app->user->identity;
    if (!$user->repair_id) {
      return Re::data(null, '您还不是维修员，暂时无法接单', Re::ERROR);
    }
    $taskRepair = new TaskRepair();
    $taskRepair->task_id = $task_id;
    $taskRepair->repair_id = $user->repair_id;
    $taskRepair->user_id = Yii::$app->user->id;
    $taskRepair->state = 1;
    $taskRepair->status = 1;
    $taskRepair->created_at = time();
    if (!$taskRepair->save()) {
      return Re::data(null, '接单失败', Re::ERROR);
    }
    $task_info->state = 1;
    $task_info->save();
    $extra = [
      'push_type' => 'qxjd',
      'task_id' => $task_id,
      'state' => $task_info->state,
      'state_name' => $this->task_state_arr[$task_info->state],
      'push_user_type' => 1
    ];
    JPushHelper::pushNotifyByReg((string)$task_info->user_id, '抢修订单接单通知', '您的抢修单已接单，请至抢修详情查看', $extra);
    return Re::data();
  }

  //维修员已出发
  public function actionRepairUserGo(){
    $task_id = Yii::$app->request->post('task_id', '');
    $longitude = Yii::$app->request->post('longitude', '119.986685');
    $latitude = Yii::$app->request->post('latitude', '31.813947');
    $estimate_distance = Yii::$app->request->post('estimate_distance', '');
    $estimate_time = Yii::$app->request->post('estimate_time', '');
    $arrive_at = Yii::$app->request->post('arrive_at', 0);
    if (empty($longitude) || empty($latitude) || empty($arrive_at)) {
      return Re::data(null, '参数错误', Re::ERROR);
    }
    $task_info = Task::findOne($task_id);
    if (!$task_info) {
      return Re::data(null, '任务信息读取失败', Re::ERROR);
    }
    $taskRepair = TaskRepair::find()->where(['task_id' => $task_id, 'user_id' => Yii::$app->user->id])->one();
    if (!$taskRepair) {
      return Re::data(null, '未读取到维修记录', Re::ERROR);
    }
    $taskRepair->lng = $longitude;
    $taskRepair->lat = $latitude;
    $taskRepair->estimate_distance = $estimate_distance;
    $taskRepair->estimate_time = $estimate_time;
    $taskRepair->arrive_at = $arrive_at;
    $taskRepair->go_at = time();
    $taskRepair->state = 2;
    if (!$taskRepair->save()) {
      return Re::data(null, '操作失败', Re::ERROR);
    }
    $task_info->state = 5;
    $task_info->save();
    return Re::data();
  }

  //维修员确认到达
  public function actionRepairUserArrive(){
    $task_id = Yii::$app->request->post('task_id', '');
    $task_info = Task::findOne($task_id);
    if (!$task_info) {
      return Re::data(null, '任务信息读取失败', Re::ERROR);
    }
    $taskRepair = TaskRepair::find()->where(['task_id' => $task_id, 'user_id' => Yii::$app->user->id])->one();
    if (!$taskRepair) {
      return Re::data(null, '维修记录读取失败', Re::ERROR);
    }
    $taskRepair->arrive_at_real = time();
    $taskRepair->state = 3;
    if (!$taskRepair->save()) {
      return Re::data(null, '操作失败', Re::ERROR);
    }
    $task_info->state = 5;
    $task_info->save();
    return Re::data();
  }

  //维修员开始/取消/完成维修 (5/4/6)
  public function actionChangeRepairState(){
    $task_id = Yii::$app->request->post('task_id', '');
    $imgs = Yii::$app->request->post('imgs', '');
    $content = Yii::$app->request->post('content', '');
    $repair_type = Yii::$app->request->post('repair_type', 5);
    $province = Yii::$app->request->post('province', '');
    $city = Yii::$app->request->post('city', '');
    $area = Yii::$app->request->post('area', '');
    $longitude = Yii::$app->request->post('longitude', '');
    $latitude = Yii::$app->request->post('latitude', '');
    $cost = Yii::$app->request->post('cost', '');
    $task_info = Task::findOne($task_id);
    if (!$task_info) {
      return Re::data(null, '任务信息读取失败', Re::ERROR);
    }
    $taskRepair = TaskRepair::find()->where(['task_id' => $task_id, 'user_id' => Yii::$app->user->id])->one();
    if (!$taskRepair) {
      return Re::data(null, '维修记录读取失败', Re::ERROR);
    }
    $taskRepair->state = $repair_type;
    if ($repair_type == 4) {
      $taskRepair->cancel_at = time();
    }
    if ($repair_type == 4 || $repair_type == 5) {
      $taskRepair->cost = $cost;
      $taskRepair->start_imgs = $imgs;
      $taskRepair->start_content = $content;
    } else {
      $taskRepair->finsh_imgs = $imgs;
      $taskRepair->finsh_content = $content;
      $taskRepair->finsh_at = time();
    }
    if (!$taskRepair->save()) {
      return Re::data(null, '操作失败', Re::ERROR);
    }
    if ($repair_type == 6) {
      $task_info->state = 2;
    } else {
      $task_info->state = $repair_type;
    }
    $task_info->save();
    if ($repair_type == 5) {
      $taskRepairLocation = new TaskRepairLocation();
      $taskRepairLocation->task_repair_id = $taskRepair->id;
      $taskRepairLocation->lng = $longitude;
      $taskRepairLocation->lat = $latitude;
      $taskRepairLocation->province = $province;
      $taskRepairLocation->city = $city;
      $taskRepairLocation->area = $area;
      $taskRepairLocation->save();
    }
    if ($repair_type == 6) {
      $extra = [
        'push_type' => 'qxwc',
        'task_id' => $task_id,
        'state' => $task_info->state,
        'state_name' => $this->task_state_arr[$task_info->state],
        'push_user_type' => 1
      ];
      JPushHelper::pushNotifyByReg((string)$task_info->user_id, '抢修订单完成通知', '您的抢修单已完成，请您对抢修情况发起评价', $extra);
      $setting = Setting::findOne(1);
      if ($setting->open_push_admin) {
        $user_admin_id_arr = User::find()->where(['status' => 1, 'is_admin' => 1])->select("id")->column();
        $extra_admin = [
          'push_type' => 'qxwc',
          'push_user_type' => 3
        ];
        JPushHelper::pushNotifyByReg($user_admin_id_arr, '抢修订单完成通知', '抢修单已完成，请至后台查看', $extra_admin);
      }
    }
    return Re::data();
  }

  //管理员派单/修改派单
  public function actionAssignRepair(){
    $task_id = Yii::$app->request->post('task_id', '');
    $user_id = Yii::$app->request->post('user_id', 0);
    $type = Yii::$app->request->post('type', 1); //1:派单 2:修改派单
    $task_info = Task::findOne($task_id);
    if (!$task_info) {
      return Re::data(null, '任务信息读取失败', Re::ERROR);
    }
    $taskRepair = TaskRepair::find()->where(['task_id' => $task_id])->one();
    if ($taskRepair && $type == 1) {
      return Re::data(null, '该抢修任务已被接单，暂时无法派单', Re::ERROR);
    }
    if ($taskRepair && $taskRepair->state > 1 && $type == 2) {
      return Re::data(null, '维修员已出发，暂时无法修改派单', Re::ERROR);
    }

    /*$repair_info = Repair::findOne($repair_id);
    if (!$repair_info) {
      return Re::data(null, '维修队信息读取失败', Re::ERROR);
    }*/
    $user = User::findOne($user_id);
    if (!$user) {
      return Re::data(null, '维修人员信息读取失败，无法派单', Re::ERROR);
    }
    if (!$user->repair_id) {
      return Re::data(null, '该用户不是维修人员，无法派单', Re::ERROR);
    }

    $is_new = 1;
    if (!$taskRepair) {
      $taskRepair = new TaskRepair();
      $taskRepair->state = 1;
      $taskRepair->status = 1;
      $taskRepair->created_at = time();
      $task_info->state = 1;
      $task_info->save();
      $is_new = 0;
    }
    $taskRepair->task_id = $task_id;
    $taskRepair->repair_id = $user->repair_id;
    $taskRepair->user_id = $user_id;
    $taskRepair->admin_assign = 1;
    if (!$taskRepair->save()) {
      return Re::data(null, '接单失败', Re::ERROR);
    }
    if (!$is_new) {
      $extra = [
        'push_type' => 'qxpd',
        'push_user_type' => 2
      ];
      JPushHelper::pushNotifyByReg((string)$user->id, '派单通知', '有新的抢修单派单，请至后台查看', $extra);
    }
    return Re::data();
  }

  //维修队员列表
  public function actionRepairUserList(){
    $task_id = Yii::$app->request->post('task_id', '');
    $keyword = Yii::$app->request->post('keyword', '');
    $task_info = Task::findOne($task_id);
    if (!$task_info) {
      return Re::data(null, '任务信息读取失败', Re::ERROR);
    }
    $area_info = Area::find()->where(['level' => 2])->andWhere(['like', 'name', $task_info->area])->one();
    $repair_query = Repair::find()->where(['type' => [1,3], 'status' => 1]);
    if (!$keyword) {
      $repair_query->andWhere(['area_id' => $area_info->id]);
    } else {
      $repair_query->andWhere(['like', 'name', $keyword]);
    }
    $repair_list = $repair_query->orderBy('star_avg desc')->all();
    $repair_data = [];
    if ($repair_list) {
      foreach ($repair_list as $v) {
        $user_data = [];
        $user_list = User::find()->where(['repair_id' => $v->id])->all();
        if ($user_list) {
          foreach ($user_list as $v1) {
            $user_data[] = [
              'user_id' => $v1->id,
              'user_name' => $v1->name,
            ];
          }
        }
        $repair_data[] = [
          'id' => $v->id,
          'name' => $v->name,
          'star_avg' => $v->star_avg,
          'user_list' => $user_data
        ];
      }
    }
    return Re::data(['data' => $repair_data]);
  }

  //维修队列表
  public function actionRepairList(){
    $task_id = Yii::$app->request->post('task_id', '');
    $keyword = Yii::$app->request->post('keyword', '');
    $task_info = Task::findOne($task_id);
    if (!$task_info) {
      return Re::data(null, '任务信息读取失败', Re::ERROR);
    }
    $area_info = Area::find()->where(['level' => 2])->andWhere(['like', 'name', $task_info->area])->one();
    $repair_query = Repair::find()->where(['type' => [1,3], 'status' => 1]);
    if (!$keyword) {
      $repair_query->andWhere(['area_id' => $area_info->id]);
    } else {
      $repair_query->andWhere(['like', 'name', $keyword]);
    }
    $repair_list = $repair_query->orderBy('star_avg desc')->all();
    $repair_data = [];
    if ($repair_list) {
      foreach ($repair_list as $v) {
        $repair_data[] = [
          'id' => $v->id,
          'name' => $v->name,
          'star_avg' => $v->star_avg
        ];
      }
    }
    return Re::data(['data' => $repair_data]);
  }

  public function actionTagListForSelect(){
			$tagList = FormTag::find()->where(['type' => 5, 'status' => 1])->select('id, name')->all();
			return Re::data(['data' => $tagList]);
	}

  public function actionGetMapInfo() {
    $origin = Yii::$app->request->post('origin', '');
    $destination = Yii::$app->request->post('destination', '');
    $url = "http://api.map.baidu.com/directionlite/v1/driving?origin=".$origin."&destination=".$destination."&ak=gpaQ70TiisiwdLpcLNi5cjnUxGBRb0af";
    $curl = curl_init();
    $method = "GET";
    curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_TIMEOUT, 3);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2);
    curl_setopt($curl, CURLOPT_HEADER, false);
    curl_setopt($curl, CURLOPT_URL, $url);
    $res = json_decode(curl_exec($curl));
    $res_map = $res->result->routes[0];
    curl_close($curl);
    $data = [
      'distance' => $res_map->distance,
      'duration' => $res_map->duration
    ];
    return Re::data(['data' => $data]);
  }
}
